package com.example.yiwei.crm.view.activity.customerActivity;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.BaseActivity;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.dockDao;
import com.example.yiwei.crm.dao_impl.dockDaoImpl;
import com.example.yiwei.crm.entity.CommunicateLogEntity;
import com.example.yiwei.crm.entity.CustomerMessageEntity;
import com.example.yiwei.crm.view.Class.listviewClass.AutoListView;
import com.example.yiwei.crm.view.activity.menuActivity.HomeActivity;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class CustomerSimpleCommunicateLogActivity extends BaseActivity implements AutoListView.OnRefreshListener,AutoListView.OnLoadListener,View.OnClickListener{
    List<CommunicateLogEntity>list1;
    ImageView fabIconStar;
    FloatingActionMenu leftCenterMenu;
    FloatingActionButton leftCenterButton;
    ImageView lcIcon1 ;
    private ImageView img_shouye,img_more1;
    private PopupWindow mPopWindow;
    private SharedPreferences sp;
    ImageView img_back,img_add;
    AutoListView lstv;
    MyAdapter ladapter;
    int a=1;
    int page=1;
    int customer_id;
    List<CommunicateLogEntity> communicateLogEntityList;
    //    List<CommunicateLogEntity> list;
    MyAdapter ldapter;
    List<CustomerMessageEntity> customerList;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            List<CommunicateLogEntity> result = (List<CommunicateLogEntity>) msg.obj;
            switch (msg.what) {
                case AutoListView.REFRESH:
                    lstv.onRefreshComplete();
                    if (communicateLogEntityList!=null){
                        communicateLogEntityList.clear();
                    }
                    if (communicateLogEntityList!=null){
                        communicateLogEntityList.addAll(result);
                    }else {
                        communicateLogEntityList= result;
                    }
                    if (a==1){
                        ladapter = new MyAdapter();
                        lstv.setAdapter(ladapter);
                        a++;
                    }

                    break;
                case AutoListView.LOAD:
                    lstv.onLoadComplete();
                    if (result!=null){
                        communicateLogEntityList.addAll(result);
                    }
                    break;
            }
//            lstv.setResultSize(result.size());
            ladapter.notifyDataSetChanged();

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_simple_communicate_log);
        lstv= (AutoListView) findViewById(R.id.coording_communication_lstv);
        lstv.setDivider(new ColorDrawable(Color.rgb(216, 216, 216)));
        lstv.setDividerHeight(1);
        lstv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        lstv.setOnRefreshListener(this);
        lstv.setOnLoadListener(this);
        customer_id = getIntent().getIntExtra("customerid",0);
        list1=new ArrayList<>();
        img_shouye= (ImageView) findViewById(R.id.simple_coording_img_shouye);
        img_more1= (ImageView) findViewById(R.id.simple_coording_img_more);
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        img_back= (ImageView) findViewById(R.id.coording_communication_btn_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                dockDao dockDao=new dockDaoImpl();
                JSONObject object=new JSONObject();
                try {
                    object.put("DEL01",0);
                    object.put("KAA01",getIntent().getExtras().getInt("customerid"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json=object.toString();
                communicateLogEntityList=new ArrayList<CommunicateLogEntity>();
                communicateLogEntityList=dockDao.queryCoordingCommunicateMessage(baseClass.find_customer_comm_URL+1,json);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if ( communicateLogEntityList==null){
                            lstv.setVisibility(View.GONE);
                            Toast.makeText(CustomerSimpleCommunicateLogActivity.this, "没有沟通日志", Toast.LENGTH_SHORT).show();
                        }else{
                            ladapter=new MyAdapter();
                            lstv.setAdapter(ladapter);
                            ladapter.notifyDataSetChanged();
                            a++;
                        }
                    }
                });
            }
        }).start();
        addXuanFu1();
        //悬浮按钮的监听
        leftCenterMenu.setStateChangeListener(new FloatingActionMenu.MenuStateChangeListener() {
            @Override
            public void onMenuOpened(FloatingActionMenu floatingActionMenu) {
                /*
                /构建两层按钮可使两个menu的点击按钮重合，当点击外层按钮用open方法使内层按钮展开，关闭同理
                 */
//                leftCenterMenu1.open(true);
                // 增加按钮中的+号图标顺时针旋转45度
//                // Rotate the icon of rightLowerButton 45 degrees clockwise
//                icon.setRotation(0);
//                PropertyValuesHolder pvhR = PropertyValuesHolder.ofFloat(View.ROTATION, 45);
//                ObjectAnimator animation = ObjectAnimator.ofPropertyValuesHolder(icon, pvhR);
//                animation.start();
                //按钮的初始角度
                fabIconStar.setRotation(0);
                //按钮的旋转角度
                PropertyValuesHolder pvhR = PropertyValuesHolder.ofFloat(View.ROTATION, 45);
                ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabIconStar, pvhR);
                animator.start();

            }

            @Override
            public void onMenuClosed(FloatingActionMenu floatingActionMenu) {
//                leftCenterMenu1.close(true);
                fabIconStar.setRotation(45);
                PropertyValuesHolder pvhR = PropertyValuesHolder.ofFloat(View.ROTATION, 0);
                ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabIconStar, pvhR);
                animator.start();
            }
        });
        lcIcon1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(CustomerSimpleCommunicateLogActivity.this,CustomerAddCommActivity.class);
                intent.putExtra("customerid",customer_id);
                Log.d("cccc",customer_id+"");
                startActivity(intent);
            }
        });
        img_more1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow();
            }
        });
        img_shouye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CustomerSimpleCommunicateLogActivity.this, HomeActivity.class);
                intent.putExtra("tag","back");
                startActivity(intent);
            }
        });
    }
    private void loadData(int refresh) {
        if (refresh== AutoListView.REFRESH){
            UpdateTextTask updateTextTask = new UpdateTextTask();
            updateTextTask.execute();
        }else if(refresh== AutoListView.LOAD){
            LoadTask loadTask = new LoadTask();
            loadTask.execute();
        }

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.customer_apo:
                Intent intent2 = new Intent(CustomerSimpleCommunicateLogActivity.this,SimpleCustomerApoActivity.class);
                intent2.putExtra("customerid",customer_id);
                startActivity(intent2);
                break;
            case R.id.customer_team:
                Intent intent3 = new Intent(CustomerSimpleCommunicateLogActivity.this,TeamMembersActivity.class);
                intent3.putExtra("customerid",customer_id);
                startActivity(intent3);
                break;
            case R.id.customer_operation_log:
                Intent intent1 = new Intent(CustomerSimpleCommunicateLogActivity.this,CustomerOperationLogActivity.class);
                intent1.putExtra("customerid",customer_id);
                startActivity(intent1);
                break;
        }
    }

    class UpdateTextTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {
            int what = 0;
            msg.what = what;
            page =1;
            dockDao dockDao=new dockDaoImpl();
            JSONObject object=new JSONObject();
            try {
                object.put("DEL01",0);
                object.put("KAA01",getIntent().getExtras().getInt("customerid"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String json=object.toString();
            list1=dockDao.queryCoordingCommunicateMessage(baseClass.find_customer_comm_URL+1,json);
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            if (list1!=null){
                if (lstv.getVisibility()==View.GONE){
                    lstv.setVisibility(View.VISIBLE);
                }
                msg.obj = list1;
                handler.sendMessage(msg);
            }else {
                lstv.setVisibility(View.GONE);
                Toast.makeText(CustomerSimpleCommunicateLogActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(integer);
        }
    }
    class LoadTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {
            int what = 1;
            msg.what = what;
            page=page+1;
            dockDao dockDao=new dockDaoImpl();
            JSONObject object=new JSONObject();
            try {
                object.put("DEL01",0);
                object.put("KAA01",getIntent().getExtras().getInt("customerid"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String json=object.toString();
            list1=dockDao.queryCoordingCommunicateMessage(baseClass.find_customer_comm_URL+page,json);
            return null;
        }
        @Override
        protected void onPostExecute(Integer integer) {
            if (list1!=null){
                msg.obj = list1;
                handler.sendMessage(msg);
            }else {
                msg.obj = list1;
                handler.sendMessage(msg);
                Toast.makeText(CustomerSimpleCommunicateLogActivity.this, "无更多数据", Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(integer);
        }
    }
    @Override
    public void onLoad() {
        loadData(AutoListView.LOAD);
    }

    @Override
    public void onRefresh() {
        loadData(AutoListView.REFRESH);
    }
    @Override
    protected void onRestart() {
        super.onRestart();
            onRefresh();
    }
    private void showPopupWindow() {
        View contentView = LayoutInflater.from(CustomerSimpleCommunicateLogActivity.this).inflate(
                R.layout.popowindow_customer_comm, null);

        mPopWindow = new PopupWindow(contentView);
        mPopWindow.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopWindow.setHeight( LinearLayout.LayoutParams.WRAP_CONTENT);

        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = contentView.getMeasuredWidth();    //  获取测量后的宽度
        int popupHeight = contentView.getMeasuredHeight();  //获取测量后的高度
        int[] location = new int[2];
        TextView tv1 = (TextView) contentView.findViewById(R.id.customer_apo);
        TextView tv3 = (TextView) contentView.findViewById(R.id.customer_team);
        TextView tv5 = (TextView) contentView.findViewById(R.id.customer_operation_log);
        tv1.setOnClickListener(this);
        tv3.setOnClickListener(this);
        tv5.setOnClickListener(this);
        img_more1.getLocationOnScreen(location);
        mPopWindow.setAnimationStyle(R.style.contextMenuAnim);
        mPopWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.pop_bg));
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);   //设置外部点击关闭ppw窗口
        mPopWindow.setFocusable(true);
        mPopWindow.update();

        mPopWindow.showAtLocation(img_more1, Gravity.NO_GRAVITY, (location[0] + img_more1.getWidth() / 2) - popupWidth / 2, location[1] - img_more1.getHeight()/2-popupHeight);

    }
    public void  addXuanFu1(){
        /**
         * 一个FloatingActionButton有一个FloatingActionMenu，FloatingActionMenu添加动画弹出的子菜单。
         * FloatingActionButton的按钮点击事件将触发、弹出FloatingActionMenu中包含的子菜单。
         * FloatingActionMenu使用attachTo方法附着在一个FloatingActionButton上。
         * FloatingActionMenu在attachTo到一个FloatingActionButton后，两者之间发生关联。
         * FloatingActionMenu在添加子菜单时候，首先需要一个SubActionButton.Builder，该SubActionButton.
         * Builder通过setContentView(ImageView
         * image).build()把一个ImageView创建生产一个SubActionButton ,
         * 然后通过FloatingActionMenu.Builder的add方法把前面生成的SubActionButton添加进去。
         *
         *
         * 按钮的旋转动画在onMenuOpened和onMenuClosed中做。
         *
         */
        WindowManager wm = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        //按钮的大小
        int redActionButtonSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_size1);
        //距离下边的长度
        int redActionButtonMargin = 7;
        //距离右边的长度
        int redActionButtonMarginRight = width/2-getResources().getDimensionPixelSize(R.dimen.red_action_button_content_size)/2;
        //按钮中内容的大小
        int redActionButtonContentSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_size);
        int redActionButtonContentMargin = getResources()
                .getDimensionPixelSize(R.dimen.red_action_button_content_margin);
        //弹出圆弧的半径
        int redActionMenuRadius = getResources().getDimensionPixelSize(R.dimen.red_action_menu_radius3);
        int blueSubActionButtonSize = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_size);
        int blueSubActionButtonContentMargin = getResources()
                .getDimensionPixelSize(R.dimen.blue_sub_action_button_content_margin);

        fabIconStar = new ImageView(this);
        //按钮中的图片
        fabIconStar.setImageDrawable(getResources().getDrawable(R.drawable.plus5));

        FloatingActionButton.LayoutParams starParams = new FloatingActionButton.LayoutParams(redActionButtonSize,
                redActionButtonSize);
        starParams.setMargins(redActionButtonMargin, redActionButtonMargin, redActionButtonMarginRight,
                redActionButtonMargin);
        fabIconStar.setLayoutParams(starParams);

        FloatingActionButton.LayoutParams fabIconStarParams = new FloatingActionButton.LayoutParams(
                redActionButtonContentSize, redActionButtonContentSize);
        fabIconStarParams.setMargins(redActionButtonContentMargin, redActionButtonContentMargin,
                redActionButtonContentMargin, redActionButtonContentMargin);

        leftCenterButton = new FloatingActionButton.Builder(this)
                .setContentView(fabIconStar, fabIconStarParams)
                .setBackgroundDrawable(R.drawable.button_action_red_selector)// 设置变化时的背景色
                .setPosition(FloatingActionButton.POSITION_BOTTOM_RIGHT)// 靠近右边和下边
                .setLayoutParams(starParams).build();

        // Set up customized SubActionButtons for the right center menu
        SubActionButton.Builder lCSubBuilder = new SubActionButton.Builder(this);
        lCSubBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_action_blue_selector));

        FrameLayout.LayoutParams blueContentParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);
        blueContentParams.setMargins(blueSubActionButtonContentMargin, blueSubActionButtonContentMargin,
                blueSubActionButtonContentMargin, blueSubActionButtonContentMargin);
        lCSubBuilder.setLayoutParams(blueContentParams);
        // Set custom layout params
        FrameLayout.LayoutParams blueParams = new FrameLayout.LayoutParams(blueSubActionButtonSize,
                blueSubActionButtonSize);
        lCSubBuilder.setLayoutParams(blueParams);

//        ImageView lcIcon1 = new ImageView(this);
//        ImageView lcIcon2 = new ImageView(this);
//        ImageView lcIcon3 = new ImageView(this);
//
//        lcIcon1.setImageDrawable(getResources().getDrawable(R.drawable.u116));
//        lcIcon2.setImageDrawable(getResources().getDrawable(R.drawable.u117));
//        lcIcon3.setImageDrawable(getResources().getDrawable(R.drawable.u118));
        //添加按钮
        lcIcon1 = new ImageView(this);

//         lcIcon4 = new TextView(this);
        lcIcon1.setImageDrawable(getResources().getDrawable(R.drawable.u1191));
//        lcIcon4.setText("选择部门");

        // Build another menu with custom options
        leftCenterMenu = new FloatingActionMenu.Builder(this)
                .addSubActionView(lCSubBuilder.setContentView(lcIcon1, blueContentParams).build())
                .setRadius(redActionMenuRadius).setStartAngle(270).setEndAngle(300).attachTo(leftCenterButton).build();



    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            FloatingActionMenu v = leftCenterMenu;
            if (isShouldHideKeyboard(v, ev)) {
//                Toast.makeText(this, aBoolean+"", Toast.LENGTH_SHORT).show();
                if (leftCenterMenu.isOpen()){
                    leftCenterMenu.close(true);
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据控件所在坐标和用户点击的坐标相对比，来判断是否隐藏，因为当用户点击控件时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(FloatingActionMenu v, MotionEvent event) {
        if (v != null ) {
            int[] l = {100, 100};
            int left = l[0],
                    top = l[1],
                    bottom = top ,
                    right = left ;
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击控件的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是控件则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }
    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return communicateLogEntityList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {

            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.communicate_listview,null);
                holder = new ViewHolder();
                holder.txt_time= (TextView) convertView.findViewById(R.id.communicate_listview_txt_next_time);
                holder.txt_cotent= (TextView) convertView.findViewById(R.id.communication_listview_txt_cotent);
                holder.txt_manager = (TextView) convertView.findViewById(R.id.communication_listview_txt_manager);
                holder.txt_state= (TextView) convertView.findViewById(R.id.communication_listview_txt_state);
                holder.tv1 = (TextView) convertView.findViewById(R.id.comm_item_time);
                holder.tv2 = (TextView) convertView.findViewById(R.id.comm_item_manger);
                holder.tv3 = (TextView) convertView.findViewById(R.id.comm_item_connect);
                holder.im1 = (ImageView) convertView.findViewById(R.id.comm_item_im);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (communicateLogEntityList.get(position).getIs_communication()==0){
                holder.txt_state.setText("未");
                holder.im1.setImageDrawable(getResources().getDrawable(R.drawable.comm));
                holder.txt_state.setTextColor(getResources().getColor(R.color.commcolor));
                holder.txt_cotent.setTextColor(getResources().getColor(R.color.commcolor));
                holder.txt_manager.setTextColor(getResources().getColor(R.color.commcolor));
                holder.txt_time.setTextColor(getResources().getColor(R.color.commcolor));
                holder.tv1.setTextColor(getResources().getColor(R.color.commcolor));
                holder.tv2.setTextColor(getResources().getColor(R.color.commcolor));
                holder.tv3.setTextColor(getResources().getColor(R.color.commcolor));
            }else if(communicateLogEntityList.get(position).getIs_communication()==1){
                holder.txt_state.setText("已");
                holder.im1.setImageDrawable(getResources().getDrawable(R.drawable.ycomm));
                holder.txt_state.setTextColor(getResources().getColor(R.color.title_color));
                holder.txt_cotent.setTextColor(getResources().getColor(R.color.title_color));
                holder.txt_manager.setTextColor(getResources().getColor(R.color.title_color));
                holder.txt_time.setTextColor(getResources().getColor(R.color.title_color));
                holder.tv1.setTextColor(getResources().getColor(R.color.title_color));
                holder.tv2.setTextColor(getResources().getColor(R.color.title_color));
                holder.tv3.setTextColor(getResources().getColor(R.color.title_color));
            }
            holder.txt_cotent.setText(communicateLogEntityList.get(position).getCommunication_content());
            holder.txt_manager.setText(communicateLogEntityList.get(position).getCommunication_manager_name());
            if (communicateLogEntityList.get(position).getNext_communicate_date()!=null){
                SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                String time = communicateLogEntityList.get(position).getNext_communicate_date();
                long l = Long.parseLong(time);
                Date date = new Date(l);
                String create_time = sdf.format(date);
                holder.txt_time.setText(create_time);
            }
            return convertView;
        }
        class ViewHolder {
            TextView txt_time,txt_cotent,txt_manager,txt_state,tv1,tv2,tv3;
            ImageView im1;
        }
    }
}
